<?php

namespace Lims\DebtorBundle\Controller;

use DateTime;
use Exception;
use Lims\DebtorBundle\Controller\DebtorController;
use Lims\MainBundle\Entity\Citizen;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Utils\SecurityBundle\CustomClass\SecurityFunctions;

class CitizenController extends Controller
{
    private $msg = null;
    private $security;
    private $em;

//    public function __construct()
//    {
//    }


    public function listAction()
    {
        return $this->render('LimsDebtorBundle:Citizen:list.html.twig', array());
    }
    
    public function newAction()
    {
        $user = $this->checkIsLoggedIn();    
        $em = $this->getDoctrine()->getManager();
        $aimagDuuregList = $em->getRepository('LimsMainBundle:AimagDuureg')->findForList();
        $sumKhorooList = $em->getRepository('LimsMainBundle:SumKhoroo')->findForList();        
        $jobPositionList = $em->getRepository('LimsMainBundle:JobPosition')->getJobPositionList();
        
        return $this->render('LimsDebtorBundle:Citizen:new.html.twig', array(
            'aimagDuuregList' => $aimagDuuregList, 
            'sumKhorooList' => $sumKhorooList,
            'jobPositionList' => $jobPositionList
        ));
    }
    
    public function editAction()
    {
        return $this->render('LimsDebtorBundle:Citizen:edit.html.twig', array());
    }
    
    public function createAction(Request $request)
    {
        $user = $this->checkIsLoggedIn();
//        $defaultData = array('message' => 'Type your message here');
//        $form = $this->createFormBuilder($defaultData)
//            ->add('citizen_family_name', 'text')
//            ->add('citizen_job_email', 'email')
//            ->add('citizen_job_address', 'textarea')
//            ->add('save', 'submit')
//            ->getForm();
//    
//        $form->handleRequest($request);
        
        $citizenData = $this->checkCitizenNew();
        
        if($this->msg != null)
        {
            $this->get('session')->getFlashBag()->add('error', $this->msg);
            return new RedirectResponse($this->getRequest()->headers->get('referer'));
        }
        
        $em = $this->getDoctrine()->getManager();
        
        try{
            // SAVE CITIZEN                  
            $citizenObject = $em->getRepository('LimsMainBundle:Citizen')->saveCitizen($em, $citizenData, $this->container->get('security.context')->getToken()->getUser()->getId());
            
            // SAVE DEBTOR
            $debtor = $em->getRepository('LimsMainBundle:Debtor')->saveCitizenDebtor($em, $this->container->get('security.context')->getToken()->getUser()->getId(), $citizenObject, null);
            
            // SAVE PHONE
            if($citizenData['citizen_phone'] != null){
                foreach($citizenData['citizen_phone'] AS $phone){
                    $phone = SecurityFunctions::clear($phone);
                    $phoneObject = $em->getRepository('LimsMainBundle:Phone')->savePhone($em, $this->container->get('security.context')->getToken()->getUser()->getId(), $debtor, $phone);
                }
            }
            
            // SAVE EMAIL
            if($citizenData['citizen_email'] != null){
                foreach($citizenData['citizen_email'] AS $email){
                    $email = SecurityFunctions::clear($email);
                    $emailObject = $em->getRepository('LimsMainBundle:Email')->saveEmail($em, $this->container->get('security.context')->getToken()->getUser()->getId(), $debtor, $email);
                }
            }
            
            // SAVE JOB
            if($citizenData['citizen_has_job'] == 1)
            {
                $jobObject = $em->getRepository('LimsMainBundle:Job')->saveJob($em, $citizenData, $citizenObject, $this->container->get('security.context')->getToken()->getUser()->getId());
            }
            
            
            $em->flush();
            
            $this->get('session')->getFlashBag()->add('notice', 'Амжилттай нэмлээ');
        }  catch (Exception $e)
        {
            $this->get('session')->getFlashBag()->add('error', 'Үйлдэл амжилтгүй боллоо');
            return new RedirectResponse($this->generateUrl('lims_debtor_list'));
        }
        
        if($citizenObject == false)
        {
            $this->get('session')->getFlashBag()->add('error', 'Үйлдэл амжилтгүй боллоо');
            return new RedirectResponse($this->getRequest()->headers->get('referer'));
        }
        return new RedirectResponse($this->generateUrl('lims_credit_new', array('registerNumber' => $citizenObject->getRegisterNumber())));
    }

    /**
     * Get data from post
     * @return type
     */
    private function checkCitizenNew()
    {
        $citizenData = array();
        
        /**
         * REGISTER NUMBER шалгуур
         */
        if(!isset($_POST['citizen_register_number']))
        {
            $this->msg .= $this->container->getParameter('ERROR_MSG_CITIZEN_1');
        }else if(strlen($_POST['citizen_register_number']) == 0)
        {
            $this->msg .= $this->container->getParameter('ERROR_MSG_CITIZEN_1');   
        }else{
            $citizenData['citizen_register_number'] = SecurityFunctions::clear($_POST['citizen_register_number']);
        }
        
        $citizenData['citizen_family_name'] = SecurityFunctions::clear(isset($_POST['citizen_register_number']) ? $_POST['citizen_register_number'] : null);
        $citizenData['citizen_last_name'] = SecurityFunctions::clear(isset($_POST['citizen_last_name']) ? $_POST['citizen_last_name'] : null);
        $citizenData['citizen_first_name'] = SecurityFunctions::clear(isset($_POST['citizen_first_name']) ? $_POST['citizen_first_name'] : null);
        $citizenData['citizen_is_married'] = SecurityFunctions::clear(isset($_POST['citizen_is_married']) ? $_POST['citizen_is_married'] : null);
        $citizenData['citizen_address_1'] = SecurityFunctions::clear(isset($_POST['citizen_address_1']) ? $_POST['citizen_address_1'] : null);
        $citizenData['citizen_address_2'] = SecurityFunctions::clear(isset($_POST['citizen_address_2']) ? $_POST['citizen_address_2'] : null);
        $citizenData['citizen_address_full'] = SecurityFunctions::clear(isset($_POST['citizen_address_full']) ? $_POST['citizen_address_full'] : null);
        $citizenData['citizen_has_job'] = SecurityFunctions::clear(isset($_POST['citizen_has_job']) ? $_POST['citizen_has_job'] : null);
        $citizenData['citizen_job_position_id'] = SecurityFunctions::clear(isset($_POST['citizen_job_position_id']) ? $_POST['citizen_job_position_id'] : null);
        $citizenData['citizen_job_name'] = SecurityFunctions::clear(isset($_POST['citizen_job_name']) ? $_POST['citizen_job_name'] : null);        
        $citizenData['citizen_job_address'] = SecurityFunctions::clear(isset($_POST['citizen_job_address']) ? $_POST['citizen_job_address'] : null);
        $citizenData['citizen_job_phone_number'] = SecurityFunctions::clear(isset($_POST['citizen_job_phone_number']) ? $_POST['citizen_job_phone_number'] : null);
        $citizenData['citizen_job_email'] = SecurityFunctions::clear(isset($_POST['citizen_job_email']) ? $_POST['citizen_job_email'] : null);
        // Phone
        $citizenData['citizen_phone'] = SecurityFunctions::clearArray(isset($_POST['citizen_phone']) ? $_POST['citizen_phone'] : null);
        // Email
        $citizenData['citizen_email'] = SecurityFunctions::clearArray(isset($_POST['citizen_email']) ? $_POST['citizen_email'] : null);
        
        
        
        return $citizenData;
    }
    
 
    
    private function checkIsLoggedIn()
    {
		if('anon.' == $this->container->get('security.context')->getToken()->getUser())
		{
			header("Location: /exit/");
		}
		
        if($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') === FALSE)
        {
            header("Location: /exit/");
        }else{
            return $this->container->get('security.context')->getToken()->getUser();
        }
    }
    
}
